package completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static ExecutorService executor = Executors.newCachedThreadPool();

    static void runWithLog(CompletableFuture<String> future, String taskName) {
        future.whenComplete((result, throwable) -> {
            if (throwable == null) {
                System.out.println(taskName + " has been completed successfully.");
            } else {
                System.out.println(taskName + " has failed: " + throwable.getMessage());
            }
        });
    }
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            MyUtil.sleep(1000);
            // int i = 1 / 0;
            return "hello,word";
        }, executor);
        runWithLog(future, "task1");
        // System.out.println("before get()");
        // String s = null;
        // try {
        //     s = future.get();
        // } catch (InterruptedException e) {
        //     e.printStackTrace();
        // } catch (ExecutionException e) {
        //     e.printStackTrace();
        // }
        // System.out.println(s);
        executor.shutdown();
    }
}